const mammoth = require('mammoth');
const { setImageWrapping } = require('mammoth-docx-styles');
const fs = require('fs');
const path = require('path');

// 示例 HTML 内容
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <img src="path/to/your/image.jpg" alt="示例图片">
    <p>这是一段示例文本，图片将以四周环绕的方式显示在文档中。</p>
</body>
</html>
`;

// 定义转换选项
const options = {
    convertImage: mammoth.images.imgElement(function (element) {
        return mammoth.images.dataUri(element);
    })
};

// 执行转换
mammoth.convertToDocx(html, options)
   .then((result) => {
        const docxBuffer = result.value;

        // 设置图片环绕方式为四周型
        const wrappedDocxBuffer = setImageWrapping(docxBuffer, 'square');

        const outputFilePath = path.join(__dirname, 'output.docx');
        fs.writeFileSync(outputFilePath, wrappedDocxBuffer);
        console.log('HTML 已成功转换为 Word 文件，文件保存为 output.docx');
    })
   .catch((error) => {
        console.error('转换过程中出现错误:', error);
    });    